package com.zhichat.infrastructure.redis.rediskey;


import com.zhichat.infrastructure.util.ConsistentHash;
import lombok.extern.slf4j.Slf4j;

import java.time.Duration;

@Slf4j
public abstract class AbstracRedisKey implements Key {
    protected String preffix;
    protected Duration duration;
    protected boolean randome = false;

    public AbstracRedisKey(String preffix) {
        this.preffix = preffix;
        this.duration = Duration.ofDays(365);
    }

    public AbstracRedisKey(String preffix, Duration duration) {
        this.preffix = preffix;
        this.duration = duration;
    }

    public AbstracRedisKey(String preffix, boolean randome) {
        this.preffix = preffix;
        this.duration = Duration.ofDays(365);
        this.randome = randome;
    }

    @Override
    public Duration duration() {
        if (randome) {
            int t = ConsistentHash.getDuration(getKey());
            this.duration = Duration.ofMinutes(t);
            log.debug("超时时间,{},分钟", t);
        }
        return this.duration;
    }

    @Override
    public Duration duration(Object object) {
        if (randome) {
            int t = ConsistentHash.getDuration(getKey(object));
            this.duration = Duration.ofMinutes(t);
            log.debug("超时时间,{},分钟", t);
        }
        return this.duration;
    }

    @Override
    public Duration duration(Object... object) {
        if (randome) {
            int t = ConsistentHash.getDuration(getKey(object));
            this.duration = Duration.ofMinutes(t);
            log.debug("超时时间,{}分钟", t);
        }
        return this.duration;
    }

    @Override
    public String getKey() {
        return getClass().getSimpleName() + ":" + preffix + ":";
    }

    @Override
    public String getKey(Object o) {
        if (o == null) {
            return getKey();
        }
        return getClass().getSimpleName() + ":" + preffix + ":" + o;
    }

    @Override
    public String getKey(Object... ob) {
        if (ob == null || ob.length == 0) {
            return getKey();
        }
        StringBuilder sb = new StringBuilder();
        for (Object o : ob)
            sb.append(o).append(":");
        return getClass().getSimpleName() + ":" + preffix + ":"
                + (sb.substring(0, sb.length() - 1).toString());
    }
}
